<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Goods;

class Search extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    /**
     * @var $demandModel \app\common\model\Demand
     */
    protected $demandModel = null;

    /**
     * @var $goodsModel Goods
     */
    protected $goodsModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->demandModel = new \app\common\model\Demand();
        $this->goodsModel = new Goods();
    }

    public function index()
    {
        $keywords = input('param.keywords', '', 'trim,strip_tags,htmlspecialchars');
        $type = input('param.type', '', 'trim');
        $offset = input('param.offset',0, 'intval');
        $limit = input('param.limit',10, 'intval');
        if (!$keywords || !$type || !in_array($type,['goods','demand','shop','home'])){
            $this->error('参数错误');
        }
        if (($offset && $offset < 0) || ($limit && $limit <= 0)){
            $this->error('参数错误');
        }
        $list = [];
        switch ($type){
            case 'goods':
                $list = $this->goodsModel->with('user')->where(['verify_status'=>'allow','onshelf_status'=>1,'title'=>['like', "%".$keywords."%"]])->order('update_time','desc')->limit($offset, $limit)->select();
                break;
            case 'demand':
                $list = $this->demandModel->with('user')->where(['verify_status'=>'allow','onshelf_status'=>1,'title'=>['like', "%".$keywords."%"]])->order('update_time','desc')->limit($offset, $limit)->select();
                break;
            case 'shop':
                $list = (new \app\common\model\Shop())->where('name','like', "%".$keywords."%")->order('update_time','desc')->limit($offset, $limit)->select();
                break;
            case 'home':
                $list = (new \app\common\model\UserEnterprise())->where(['certification_status'=>1,'corporate_name'=>['like', "%".$keywords."%"]])->order('update_time','desc')->limit($offset, $limit)->select();
                break;
        }
        $this->success('', $list);
    }
}